import React, { useState, useEffect, useCallback,useContext } from 'react'
import { useSearchParams, useNavigate, useParams } from 'react-router-dom'
import request, { baseUrl } from '../utils/request'
import { Image, NavBar, ImageViewer, Grid, Ellipsis, Button, Space, Badge } from 'antd-mobile'
import { StarOutline, HeartOutline, TruckOutline } from 'antd-mobile-icons'

import context from '@/store/context'

function Goods() {
    // 动态路由传递id: /goods/123
    let { id } = useParams();

    // 兼容url参数传递id: /goods?id=123
    const [params] = useSearchParams()
    if (!id) {
        id = params.get('id')
    }

    const [goods, setGoods] = useState({})

    // 获取购物数据
    const {cartlist,dispatch} = useContext(context)

    // 添加id作为依赖，解决同页面跳转问题
    useEffect(() => {
        getData()
    }, [id])
    const getData = async () => {
        // http://120.76.247.5:2003/api/goods/+id
        const { data } = await request.get('/goods/' + id)
        console.log('data', data)


        setGoods(data.data)
    }
    const navigate = useNavigate()
    const back = useCallback(() => {
        navigate(-1)
    }, [])

    // 大图显示
    const [visible, setVisible] = useState(false)
    const showBigImage = () => {
        setVisible(true)
    }

    // 同类热门商品
    const [hotlist, setHotlist] = useState([])
    const getList = async () => {
        if (!goods.category) return;
        const { data } = await request.get('/goods/', {
            params: {
                category: goods.category,
                sort: 'views'
            }
        })
        setHotlist(data.data.result)
    }
    useEffect(() => {
        getList()
    }, [goods])

    const gotoDetail = useCallback((id) => {
        navigate('/goods/' + id)
    }, [])
    const addToCart = ()=>{
        const {_id,goods_name,img_url,sales_price} = goods
        // 判断当前商品是否已存在购物车中
        const current = cartlist.find(item=>item._id===_id)
        if(current){
            dispatch({type:'changeqty',payload:{_id,qty:current.qty+1}})
        }else{
            const newGoods = {
                _id,goods_name,img_url,sales_price,
                qty:1
            }
            dispatch({type:'addtocart',payload:newGoods})

        }
    }
    const buyNow = ()=>{
        addToCart();
        navigate('/cart')
    }

    return <div>
        <NavBar onBack={back} right={<HeartOutline fontSize={24} />}>{goods.goods_name}</NavBar>
        <Image src={baseUrl + goods.img_url} onClick={showBigImage} />
        <h1 style={{ fontSize: 18 }}>{goods.goods_name}</h1>
        <p className='price'><del>{goods.price}</del><span>{goods.sales_price}</span></p>
        <p>已售：{goods.sales_qty}</p>

        <h3>同类热门商品</h3>
        <Grid columns={2} gap={18}>
            {
                hotlist.map(item => (
                    <Grid.Item key={item._id} onClick={gotoDetail.bind(null, item._id)}>
                        <Image src={baseUrl + item.img_url} width="100%" />
                        <Ellipsis content={item.goods_name} rows={3} expandText="展开" collapseText="收起">

                        </Ellipsis>

                        <p className='price'><del>{item.price}</del><span>{item.sales_price}</span></p>
                    </Grid.Item>

                ))
            }
        </Grid>

        <ImageViewer
            image={baseUrl + goods.big_img_url}
            visible={visible}
            defaultIndex={1}
            onClose={() => {
                setVisible(false)
            }}
        />

        <div className='actions'>


            <Grid columns={3} gap={8} style={{width:'100%'}}>
                <Grid.Item>
                    <Badge content={cartlist.length}>
                        <TruckOutline fontSize={24} onClick={()=>{
                            navigate('/cart')
                        }} />
                    </Badge>
                </Grid.Item>
                <Grid.Item span={2} style={{textAlign:'right'}}>
                    <Space justify='end'>
                        <Button color='warning' onClick={addToCart}>添加购物车</Button>
                        <Button color='danger' onClick={buyNow}>立即购买</Button>
                    </Space>
                </Grid.Item>
            </Grid>
        </div>
    </div>
}

export default Goods;